package com.leyou.trade.service.impl;

import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.ApplicationScope;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CartControllerImpl implements CartService {

    @Autowired
    private CartRepository repository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addCart(CartItem cartItem) {
        Long userId = UserContext.getUser().getId();
        String id = createId(cartItem.getSkuId());
        Optional<CartItem> optional = repository.findById(id);
        if (optional.isPresent()) {
            // 2.1.存在，记录新的商品数量
            Integer num = cartItem.getNum();
            // 2.2.获取旧的数据
            cartItem = optional.get();
            // 2.3.数量累加
            cartItem.setNum(num + cartItem.getNum());
        }
        cartItem.setId(id);
        cartItem.setUserId(userId);
        cartItem.setUpdateTime(new Date());
        repository.save(cartItem);
    }

    @Override
    public List<CartItem> findSku() {
        Long userId = UserContext.getUser().getId();

        return this.repository.findByUserId(userId, Sort.by("updateTime").descending());
    }

    @Override
    public void updateSku(Long skuId, Integer num) {
        mongoTemplate.update(CartItem.class)
                .matching(Query.query(Criteria.where("_id").is(createId(skuId))))
                .apply(Update.update("num",num).currentDate("updateTime"))
                .first();
    }

    @Override
    public void deleteSku(Long skuId) {

        this.repository.deleteById(createId(skuId)); //调用createID方法
    }

    @Override
    public void addCartItemList(List<CartItem> cartItems) {

        Long id = UserContext.getUser().getId();
        List<CartItem> list = cartItems.stream().map(cartItem -> handleUpdateItem(id, cartItem)).collect(Collectors.toList());
        repository.saveAll(list);
    }

    //将Long类型的ID 装换为 String 类型的ID
    private String createId(Long skuId) {
        return String.format("u%ds%d", UserContext.getUser().getId(), skuId);
    }

    private CartItem handleUpdateItem(Long userId,CartItem cartItem){

        Optional<CartItem> optional = repository.findById(createId(cartItem.getSkuId()));
        if (optional.isPresent()){
            Integer num = cartItem.getNum();
            cartItem = optional.get();
            cartItem.setNum(num + cartItem.getNum());
        }
        cartItem.setUserId(userId);
        cartItem.setUpdateTime(new Date());
        return cartItem;
    }
}
